﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Manage_EditUser : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            string id = Request.Params["uid"];
            if (id != null && id != "")
            {
                TreasurerDataContext db = new TreasurerDataContext();
                var q = from aU in db.Users
                        where aU.ID == id
                        select aU;
                if (q.Count() > 0)
                {
                    //修改用户信息
                    if (!"admin".Equals(Session["Current_User_Id"])
                        && !id.Equals(Session["Current_User_Id"]))
                    {
                        Response.Write("<script>alert('您无权修改他人信息。');document.location='./ListUsers.aspx';</script>");
                    }

                    Users u = q.First();

                    IdText.Text = u.ID;
                    NameText.Text = u.Name;

                    IdText.ReadOnly = true;
                    PasswordRequired.Enabled = false;
                    ConfirmCompare.Enabled = false;
                }
            }
        }
    }

    protected void SaveButton_Click(object sender, EventArgs e)
    {
        string id = IdText.Text.Trim();
        string password = PasswordText.Text.Trim();
        string name = NameText.Text.Trim();

        Users u;
        TreasurerDataContext db = new TreasurerDataContext();
        var q = from aU in db.Users
                where aU.ID == id
                select aU;

        if (password == "")
        {
            //进行更新
            u = q.First();
            u.Name = name;

            db.SubmitChanges();
        }
        else
        {
            //增加新用户
            if (q.Count() > 0)
            {
                //已经存在相同的用户名
                ErrorText.Text = "已经存在相同的用户名。";
                return;
            }
            else
            {
                u = new Users();
                u.ID = id;
                u.Password = password;
                u.Name = name;
                db.Users.InsertOnSubmit(u);

                db.SubmitChanges();
            }
        }

        Response.Write("<script>alert('用户信息保存成功。');document.location='./ListUsers.aspx';</script>");
    }
    protected void ChangePassword_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/Manage/ChangePassword.aspx");
    }
}